package chen.yi.component.operate.log;

import chen.yi.component.operate.log.aspect.MyLogAspect;
import chen.yi.component.operate.log.config.UsernameScanner;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * log日志配置类
 *
 * @author huat
 **/
@Slf4j
@Configuration
@MapperScan(basePackages = "chen.yi.component.operate.log.mapper")
@ComponentScan(basePackages = "chen.yi.component.operate.log")
public class OperateLogApplication {
    @Autowired
    private DataSource dataSource;

    @Bean
    public MyLogAspect myLogAspect() throws SQLException {
        try {
            UsernameScanner.scan();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info(" IUserInfo注入成功");
        executeSql();
        log.info(" SQL脚本执行成功");
        return new MyLogAspect();
    }

    /**
     * 初始化sql脚本文件
     */
    private void executeSql() throws SQLException {
        Connection connection = null;
        try {
            //获取链接
            connection = dataSource.getConnection();
            //不自动提交
            connection.setAutoCommit(false);
            //初始化ScriptRunner
            ScriptRunner runner = new ScriptRunner(connection);
            //遇到错误停止执行 捕获异常
            runner.setStopOnError(true);
            //按照自定义分隔符执行
            runner.setSendFullScript(false);
            //设置分隔符
            runner.setDelimiter(";");
            runner.setFullLineDelimiter(false);
            //不输出日志
            runner.setLogWriter(null);
            //读取sql脚本
            InputStream inputStream = new ClassPathResource("db/operate_log.sql").getInputStream();
            Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            runner.runScript(reader);
            connection.commit();
        } catch (SQLException | IOException e) {
            if(!Objects.isNull(connection)){
                connection.rollback();
            };
            throw new RuntimeException(e);
        } finally {
            if (!Objects.isNull(connection)) {
                connection.close();
            }
        }

    }
}
